package com.zhu.storesmanager;

import java.util.ArrayList;
import java.util.List;

import com.zhu.storesmanager.models.BrandsDataItem;
import com.zhu.storesmanager.models.DataItem;
import com.zhu.storesmanager.models.ProjectDataItem;
import com.zhu.storesmanager.models.PromoterInfoItem;
import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.models.VisitTaskInfo;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DatabaseUtil;
import com.zhu.storesmanager.utils.Log;
import com.zhu.storesmanager.utils.ViewsUtil;
import com.zhu.storesmanager.views.ChoiceView;
import com.zhu.storesmanager.views.DateView;
import com.zhu.storesmanager.views.PhotoView;
import com.zhu.storesmanager.views.PopEditText;
import com.zhu.storesmanager.views.PopMenu;
import com.zhu.storesmanager.views.StoresPromoterView;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabWidget;
import android.widget.TextView;

/**
 * 促销员信息界面
 */
public class SvStorePromoterInfoActivity extends Activity implements OnClickListener{

    //异步查询数据库token
    private final static int PROMOTER_DATA_QUERY_TOKEN = 0; //查询POSM数据
    private final static int PROJECT_DATA_QUERY_TOKEN = 1; //拜访文本数据
    private DataQueryHandler mDataQueryHandler = null; //数据异步查询Handler
    private VisitTaskInfo mVisitTaskInfo = null; //拜访门店数据
    private LayoutInflater mLayoutInflater;

    private List<PromoterInfoItem> mDataList = new ArrayList<PromoterInfoItem>(); //促销员集合
    private List<StoresPromoterView> mPromoterViewList = new ArrayList<StoresPromoterView>(); //促销员界面
    private TabHost mTabHost = null;
    private FrameLayout mFrameLayout = null;
    private PopEditText mPopEditText = null;
    private PopMenu mPopMenu = null; //弹出菜单
    private boolean isDataChange = true; //数据是否发生
    private List<ProjectDataItem> mProjectList = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Parcelable parcelable = getIntent().getParcelableExtra("info");
        mVisitTaskInfo = (VisitTaskInfo) parcelable;
        mLayoutInflater = LayoutInflater.from(this);
        setContentView(R.layout.activity_sv_storespromoter);
        setupViews();
        initData();
    }


    /**
     * 初始化界面
     */
    private void setupViews(){
        ((TextView) findViewById(R.id.title_text)).setText(R.string.promoter_info);
        findViewById(R.id.svbottom_menu_back).setOnClickListener(this);
        findViewById(R.id.svbottom_menu_save).setOnClickListener(this);
        findViewById(R.id.svbottom_menu_menu).setOnClickListener(this);
        mFrameLayout = (FrameLayout)findViewById(R.id.layout);
        mPopEditText = new PopEditText(mFrameLayout);
        mTabHost = (TabHost)findViewById(R.id.tabhost);
        mTabHost.setup();
        mPopMenu = new PopMenu(this, findViewById(R.id.bottom_menu), PopMenu.MENU_PROMOTER);
        mPopMenu.setVisitTaskInfo(mVisitTaskInfo);
    }

    /**
     * 根据促销员更新Tab
     */
    private void updateTabWidget(){
    	mTabHost.setup();
        final TabWidget tabs = mTabHost.getTabWidget();
        if(mDataList.size() > 0){
            for(PromoterInfoItem item : mDataList){   
                View tabView = getTabView(tabs, item);
                mPromoterViewList.add(getTabContentView(item));
                mTabHost.addTab(mTabHost.newTabSpec(item.mPromoterId).setIndicator(tabView).setContent(mContentFactory));
            }
        }
        mTabHost.setCurrentTab(0);
    }

    /**
     * TabContent显示内容界面
     */
    TabContentFactory mContentFactory = new TabContentFactory() {
        public View createTabContent(String tag) {
            if(mPromoterViewList.size() > 0){
                for(StoresPromoterView view : mPromoterViewList){
                    if(view.getPromoterID().equals(tag)){
                        return view;
                    }
                }
            }
            return null;
        }
    };

    /**
     * TAB 变化监听
     */
    OnTabChangeListener mOnTabChangeListener = new OnTabChangeListener(){
		@Override
		public void onTabChanged(String arg0) {
			// TODO Auto-generated method stub

		}
    };

    /**
     * 获取TAB指示界面
     * @param tabs TabWidget
     * @param item 促销员数据
     */
    private View getTabView(TabWidget tabs, PromoterInfoItem item){
        View tabView = mLayoutInflater.inflate(R.layout.tab_item, tabs, false);
        ((TextView)tabView.findViewById(R.id.tab_item_name)).setText(item.mPromoterName);
        ((TextView)tabView.findViewById(R.id.tab_item_id)).setText(item.mPromoterId);
        tabView.setTag(item);
        return tabView;
    }

    /**
     * 获取TAB内容界面
     * @param item 促销员数据
     */
    private StoresPromoterView getTabContentView(PromoterInfoItem item){
        StoresPromoterView view = (StoresPromoterView)mLayoutInflater.inflate(R.layout.view_storespromoter, null, false);
        view.setData(this, mPopEditText, item);
        return view;
    }

    /**
     * 初始化话数据
     */
    private void initData(){
    	if(!DataUtils.mUserData.isAdmin()){ //检测非管理员
    		if(mDataQueryHandler == null){
                mDataQueryHandler = new DataQueryHandler(getContentResolver()); 
            }
    		startQueryProjects();
    	}else{
    		setDataFromAdminSearchData();
    	}
    }

    /**
     * 开始查询数据库保存数据
     */
    private void startQueryPromoterDataList(){
        //查询指定门店数据
        String where = StoresManagerSettings.SupervisorStorePromoterColumns.STOREID + "=\'" + mVisitTaskInfo.mStoreId +"\' AND " + 
        StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_LAST + "=0";
        mDataQueryHandler.startQuery(PROMOTER_DATA_QUERY_TOKEN, null, 
                StoresManagerSettings.SupervisorStorePromoterColumns.CONTENT_URI_NO_NOTIFICATION,
                null, where, null, null);
    }

    /**
     * 更新数据从数据库保存的数据
     * @param cursor 数据
     */
    private void updateDataFromCursor(Cursor cursor){
        if(mDataList != null){
            mDataList.clear();
        }
        try {
            //获取数据index
            final int idIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns._ID);
            final int pidIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_ID);
            final int pnameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_NAME);
            final int inpostIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_INPOST);
            final int imageIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_IMAGE);
            final int statusIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_STATUS);
            final int badReasonIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_BADREASON);
            final int checkIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_CHECK);
            final int tmpInfoIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_TMPINFO);
            final int tmpNameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_TMPNAME);
            final int tmpTelIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_TMPTEL);
            final int notPostReasonIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_NOTPOSTREASON);
            final int problemIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_PROBLEM);
            final int photoIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_PHOTO);

            while (cursor.moveToNext()) {//遍历所有型号数据
            	boolean isSaved = cursor.getInt(cursor.getColumnIndexOrThrow(
        				StoresManagerSettings.SAVED)) == 1 ? true : false;
                PromoterInfoItem item = new PromoterInfoItem();
                item.mDBid = cursor.getLong(idIndex);
                item.mPromoterId = cursor.getString(pidIndex);
                item.mPromoterName = cursor.getString(pnameIndex);
                item.mInpost = DataUtils.updateIntDataFromHistoryData(mProjectList, cursor.getInt(inpostIndex), isSaved,
        				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 1);
                item.mImage = DataUtils.updateIntDataFromHistoryData(mProjectList, cursor.getInt(imageIndex), isSaved,
            				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 2);
                item.mStatus = DataUtils.updateIntDataFromHistoryData(mProjectList, cursor.getInt(statusIndex), isSaved,
            				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 3);
                item.mBadReason= DataUtils.updateStringDataFromHistoryData(mProjectList, cursor.getString(badReasonIndex), isSaved,
        				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 4);
                item.mCheck = DataUtils.updateIntDataFromHistoryData(mProjectList, cursor.getInt(checkIndex), isSaved,
            				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 5);
                item.mTemporary = DataUtils.updateIntDataFromHistoryData(mProjectList, cursor.getInt(tmpInfoIndex), isSaved,
            				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 6);
                item.mTempName = DataUtils.updateStringDataFromHistoryData(mProjectList, cursor.getString(tmpNameIndex), isSaved,
            				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 7);
                item.mTempTel = DataUtils.updateStringDataFromHistoryData(mProjectList, cursor.getString(tmpTelIndex), isSaved,
            				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 8);
                item.mNotPostReason = DataUtils.updateStringDataFromHistoryData(mProjectList, cursor.getString(notPostReasonIndex), isSaved,
            				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 9);
                item.mProblem = DataUtils.updateStringDataFromHistoryData(mProjectList, cursor.getString(problemIndex), isSaved,
            				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 10);
                ProjectDataItem pitem = DataUtils.getProjectDataItem(mProjectList, StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER, 11);
                if(isSaved){
                	if(pitem != null && pitem.isShow && pitem.isSave){
                		item.setImageData(cursor.getBlob(photoIndex));
                	}
                }else{
                	item.setImageData(cursor.getBlob(photoIndex));
                }
                mDataList.add(item); //添加数据项
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("SvStorePromoterInfoActivity updateDataFromCursor error");
        } finally {
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        updateTabWidget();
		if (mProjectList != null && mProjectList.size() > 0) {
			for (StoresPromoterView view : mPromoterViewList) {
				view.updateProjectDataFromCursor(mProjectList);
			}
		}
		if(mDataList.size() == 0){
			DatabaseUtil.saveVisitStatus(this, DatabaseUtil.TYPE_PROMOTER , Integer.parseInt(mVisitTaskInfo.mVisitId), 1);
		}
    }

    /**
     * 异步数据查询
     */
    private final class DataQueryHandler extends AsyncQueryHandler {
          public DataQueryHandler(ContentResolver contentResolver) {
              super(contentResolver);
          }

          /**
           * 查询结果返回
           * (non-Javadoc)
           * @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
           */
          @Override
          protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
              switch (token) {
                  case PROMOTER_DATA_QUERY_TOKEN:
                      updateDataFromCursor(cursor);
                      break;
                  case PROJECT_DATA_QUERY_TOKEN:
                	  updateProjectDataFromCursor(cursor);
                	  break;
                  default:
                      Log.e("onQueryComplete called with unknown token " + token);
              }
          }

          @Override
          protected void onDeleteComplete(int token, Object cookie, int result) {

          }
      }

    /*
     * (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v != null){
            switch(v.getId()){
                case R.id.svbottom_menu_back : //返回
                	if(!doBack()){
                        finish();
                    }
                    break;
                case R.id.svbottom_menu_save: //保存
                	saveData();
                    break;
                case R.id.svbottom_menu_menu: //菜单
                	mPopMenu.showMenu();
                	break;
            }
        }
    }

    /**
     * 数据返回
     * (non-Javadoc)
     * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	getCurStoresPromoterView().onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 获取当前促销员界面
     */
    private StoresPromoterView getCurStoresPromoterView(){
    	return mPromoterViewList.get(mTabHost.getCurrentTab());
    }

    /**
     * 保存数据
     */
    private void saveData(){
    	if(!checkSaveData()){
    		Actions.toastShort(this, getString(R.string.promoter_notnull));
    		return;
    	}
    	if(checkDataCompelete()){
    		DatabaseUtil.saveVisitStatus(this, DatabaseUtil.TYPE_PROMOTER , Integer.parseInt(mVisitTaskInfo.mVisitId), 1);
    	}else{
    		DatabaseUtil.saveVisitStatus(this, DatabaseUtil.TYPE_PROMOTER , Integer.parseInt(mVisitTaskInfo.mVisitId), 0);
    	}
    	if(mPromoterViewList.size() > 0){
    		for(StoresPromoterView view : mPromoterViewList){
    			view.saveData();
    		}
    		Actions.toastShort(this, getString(R.string.datasave_success));
    	}
    }

    /**
	 * 检测保存的数据 是否符合规则
	 * @return true 可以保存 否则反之
	 */
    private boolean checkSaveData(){
    	if(mPromoterViewList.size() > 0){
    		for(StoresPromoterView view : mPromoterViewList){
    			if(!view.checkSaveData()){
    				return false;
    			}
    		}
    	}
    	return true;
    }

    /**
	 * 检测保存的数据 是否完整
	 * @return true 可以保存 否则反之
	 */
    private boolean checkDataCompelete(){
    	if(mPromoterViewList.size() > 0){
    		for(StoresPromoterView view : mPromoterViewList){
    			if(!view.checkInputData()){
    				return false;
    			}
    		}
    	}
    	return true;
    }

    /**
     * 按键事件处理
     */
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if(!doBack()){
                finish();
            }
            return true;
        }
        return false;
    }

    /**
     * 返回事件处理
     */
    private boolean doBack(){
        if(mPopEditText != null && mPopEditText.doBack()){
            return true;
        }
        if(isDataChange){
        	if(DataUtils.mUserData.isAdmin()){
        		return false;
        	}
            popExitDialog();
            return true;
        }
        return false;
    }

    /**
     * 查询project数据
     */
    private void startQueryProjects(){
    	String where = StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE + "=" + StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER;
    	mDataQueryHandler.startQuery(PROJECT_DATA_QUERY_TOKEN, null, 
				StoresManagerSettings.DataProjectsColumns.CONTENT_URI_NO_NOTIFICATION,
				null, where, null, null);
    }

    /**
	 * 更新project数据从数据库
	 * @param cursor 数据库数据
	 */
	private void updateProjectDataFromCursor(Cursor cursor){
		mProjectList = DatabaseUtil.getProjectDataList(cursor);
		startQueryPromoterDataList();
//		if(mProjectList != null && mProjectList.size() > 0){
//			for(StoresPromoterView view : mPromoterViewList){
//				view.updateProjectDataFromCursor(mProjectList);
//			}
//		}
	}

	public List<ProjectDataItem> getProjectList(){
		return mProjectList;
	}
	/**
	 * 从管理员查询结果数据更新界面
	 */
	private void setDataFromAdminSearchData() {
		findViewById(R.id.svbottom_split_menu).setVisibility(View.GONE);
		findViewById(R.id.svbottom_menu_save).setVisibility(View.GONE);
		if (DataUtils.mQueryVisitContentResult.Data != null && DataUtils.mQueryVisitContentResult.Data.Promoters != null) {
			for(SyncModel.DataVisitContentPromoter content : DataUtils.mQueryVisitContentResult.Data.Promoters){ //遍历所有数据
				PromoterInfoItem item = new PromoterInfoItem();
				item.copyFrom(this, content);
				mDataList.add(item);
			}
			updateTabWidget();
			List<ProjectDataItem> list = DataUtils
					.getProjectDataList(StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_PROMOTER);
			if (list != null && list.size() > 0) {
				for(StoresPromoterView view : mPromoterViewList){
					view.updateProjectDataFromCursor(list);
				}
			}
		}
	}

	/**
     * 退出提示
     * 
     */
    private void popExitDialog() {
    	Actions.popExitDialog(this);
    }
}
